<?php
namespace app\index\controller;
use app\index\controller\BaseController;
use think\Db;

class MemberController  extends BaseController {

	protected function _initialize() {
		parent::_initialize();
	}

	/**
	 * 会员中心
	 */
	public function index() {
		if(!session('user_id')){
			$this->redirect('index/index/login');
		}
		//获取用户信息
		$user_info = db('member')->where('user_id',session('user_id'))->find();
		//获取用户订单信息
		$order_list = db('good_order')->where('user_id',$user_info['user_id'])->select();
		$count1 = 0;
		$count2 = 0;
		$count3 = 0;
		$count6 = 0;
		foreach($order_list as $kye=>$value){
			
			//待付款
			if($value['status']==1){
				$count1++;		
			}
			
			//待发货
			if($value['status']==2){
				$count2++;
				
			}
			//待确认
			if($value['status']==3){
				$count3++;
				
			}
			//已完成
			if($value['status']==6){
				$count6++;
				
			}
		}
		$this->assign('dfkorder', $count1);
		$this->assign('dfhorder', $count2);
		$this->assign('dqrorder', $count3);
		$this->assign('ywcorder', $count6);
		$this->assign('user_info', $user_info);
		return $this->fetch();
	}
	
	public function address() {
		$address_list =db('member_address')
						->where('user_id',session('user_id'))
						->select();
		$this->assign('address_list', $address_list);
		return $this->fetch();
	}
	
	
	public function address_add() {
		if(request()->isPost()) {
			$data = input('post.');
			$result = true;
			Db::startTrans();
			//检查用户是否有地址
			$datas['is_default'] = 1;
			$datas['province'] = $data['province'];
			$datas['city'] = $data['city'];
			$datas['district'] = $data['district'];
			$datas['consignee'] = $data['consignee'];
			$datas['mobile'] = $data['mobile'];
			$datas['address'] = $data['address'];
			$datas['user_id'] = session('user_id');
			$datas['add_time'] = now_time();
			
			if($data['id']==0){
				 db('member')->where('open_id',session("openid"))->update(['mobile'=>$data['mobile']]);
				$rest2 = db('member_address')->insert($datas);						
			}else{
				$rest2 = db('member_address')
						->where('id', $data['id'])
						->where('user_id', session('user_id'))
						->update($datas);
			}

			if(!$rest2) $result = false;
			$address = db('member_address')->where('user_id',session('user_id'))->where('is_default',1)->find(); 
			if($result){
				Db::commit();
				return  json(["code"=>200,"msg"=>"操作成功","data"=>$address]);
			}else{
				Db::rollback();
				return  json(["code"=>403,"msg"=>"操作失败"]);
			}
		}
		
		return $this->fetch();
	}
	
	function address_default(){
		if(request()->isPost()) {
			$address_id = input('address_id');
			
			if (!is_numeric($address_id)) {
				return  json(["code"=>405,"msg"=>"数据异常"]);
			}
			
			$rest1 = db('member_address')
						->where('user_id', session('user_id'))
						->update(['is_default' => 0]);
			if($rest1){
				$rest2 = db('member_address')
						->where('id', $address_id)
						->where('user_id', session('user_id'))
						->update(['is_default' => 1]);
				if($rest2){
					return  json(["code"=>200,"msg"=>"修改成功"]);
				}else{
					return  json(["code"=>403,"msg"=>"修改失败"]);
				}
			}else{
				return  json(["code"=>405,"msg"=>"修改失败"]);
			}
		}
	}
	
	
	
	
	function address_update() {
		$address_id = input('address_id');
		if (!is_numeric($address_id)) {
			return  json(["code"=>405,"msg"=>"数据异常"]);
		}
		$address_info = db('member_address')->where('id', $address_id)->where('user_id', session('user_id'))->find();

		$this->assign('address_info',$address_info);
		
		if(request()->isPost()) {
			$data = input('post.');
			unset($data['address_id']);
			$result = db('member_address')
						->where('id', $address_id)
						->where('user_id', session('user_id'))
						->update($data);
			
			if($result) {
				return  json(["code"=>200,"msg"=>"修改成功",'url'=>url('member/address')]);
			} else {
				return  json(["code"=>403,"msg"=>"修改失败"]);
			}
		}
		
		
		
		return $this->fetch();
	}
	function address_del() {
		if(request()->isPost()) {
			$address_id = input('address_id');
			
			if (!is_numeric($address_id)) {
				return  json(["code"=>405,"msg"=>"数据异常"]);
			}
			
			$result = db('member_address')->where('id', $address_id)->where('user_id', session('user_id'))->delete();
			
			if($result) {
				return  json(["code"=>200,"msg"=>"删除成功"]);
			} else {
				return  json(["code"=>403,"msg"=>"删除失败"]);
			}
		}
	}
	public function edit_password() {
		if(request()->isPost()){
			$xpassword['password']=md5_salt(input('xpassword'));
			$jpassword['password']=md5_salt(input('jpassword'));
			$user_info = db('member')->where('user_id',session('user_id'))->where($jpassword)->find();
			if($user_info){
				$rest = db('member')->where('user_id', session('user_id'))->update($xpassword);
				if($rest){
					return json(['code'=>200,'msg'=>'修改成功','url'=>'/index/index/login']);
				}else{
					return json(['code'=>405,'msg'=>'修改失败']);
				}
			}else{
				return json(['code'=>403,'msg'=>'旧密码不对']);
			}
		}
		return $this->fetch();
	}
	public function orders() {
		
		$where['user_id'] = session('user_id');
		if(input('status')>0){
			$where['status'] = input('status');
		}else{
			$where['status'] = ['<>',8];
		}
		
		//获取用户订单信息
		$order_list = db('good_order')
						->where($where)
						->order('add_time desc')
						->select();
						
		foreach($order_list as $key=>&$value){
			//获取订单详情
			$order_item = db('order_items')->where('order_id',$value['id'])->select();
			$value['order_item'] = $order_item;
		}
		$this->assign('status',input('status'));
		$this->assign('order_list',$order_list);
		return $this->fetch();
	}
	
	
	function order_page(){
		
		//获取用户订单信息
		$order_info = db('good_order')
						->where('id',input('order_id'))
						->find();
		if($order_info){
			$order_item = db('order_items')->where('order_id',$order_info['id'])->select();
			
			$order_info['order_item'] = $order_item;
			
		}else{
			return $this->fetch('none_style');
		}
		
		$this->assign('order_info',$order_info);
		return $this->fetch();
	}
	
	public function buy() {
		//获取用户地址信息
		$user_address = db('member_address')
						->where('user_id',session('user_id'))
						->where('is_default',1)
						->find();
		if(!$user_address){
			$this->redirect('member/address');
		}
		$order_ids = input('order_id');
		
		$order_arr = explode(",",$order_ids);
		
		$order_list = array();
		$total_money = 0;
		foreach($order_arr as $key=>$value){
			//获取订单信息
			$order_info = db('good_order')->where('id',$value)->find();
			$total_money = bcadd($order_info['total_price'], $total_money, 2);
			//获取订单详情
			$oreder_item  = db('order_items')->where('order_id',$order_info['id'])->select();
			$order_info['order_item'] = $oreder_item;
			$order_list[] = $order_info;
			
		}
		
		$this->assign('order_arr',$order_ids);		
		$this->assign('user_address',$user_address);
		$this->assign('order_list',$order_list);
		$this->assign('total_money',$total_money);		
		return $this->fetch();
	}
	
		
	//订单
	public function member_order(){
		$type = input("type");
		if($type!=0){
			$map['status'] = $type;
			$where['a.status'] = $type;
		}

		$map['user_id'] = session('user_id');
		$where['a.user_id'] = session('user_id');
		
		$result2 = db('order_items')->field('order_id,thumb')->select();
		
		$ordercount = db('order_items')->field('order_id,count(id) as count')->group('order_id')->buildSql();
		
		$result = db('good_order a')
				->field('a.id,a.order_sn,a.status,a.pay_price,a.add_time,c.count')
				->join($ordercount.' c','a.id=c.order_id')
				->where($where)->order('add_time desc')->select();

		$this->assign('res2',$result2);
		$this->assign('res',$result);
		$this->assign('type',$type);
		return $this->fetch();		
	}
	//个人资料
	public function update(){
			if ($this->request->isPost()) {
			$data = $this->request->post();
			$data['update_time'] = now_time();
			unset($data['file']);
			$result = db('member')->where('user_id', session('user_id'))->update($data);
			if ($result) {
				$this->success('保存成功');
			} else {
				$this->error('保存失败');
			}
		}
		$result = db('member')->where('user_id', session('user_id'))->select();
		$this->assign('res',$result);
		return $this->fetch();
		
	}
	//修改密码
	public function member_pwd(){
		if(request()->isPost()){
			$xpassword['password']=md5_salt(input('xpassword'));
			$jpassword['password']=md5_salt(input('jpassword'));
			$user_info = db('member')->where('user_id',session('user_id'))->where($jpassword)->find();
			if($user_info){
				$rest = db('member')->where('user_id', session('user_id'))->update($xpassword);
				if($rest){
					return json(['code'=>200,'msg'=>'修改成功','url'=>'/index/index/login']);
				}else{
					return json(['code'=>405,'msg'=>'修改失败']);
				}
			}else{
				return json(['code'=>403,'msg'=>'旧密码不对']);
			}
		}
		return $this->fetch();
		
	}
	
	//获取地址
	function  getaddress(){
		$address = '';
		if(session('user_id')){
			$address = db('member_address')->where('user_id',session('user_id'))->where('is_default',1)->find(); 
		}
		if($address){
			return  json(["code"=>200,"data"=>$address]);
		}else{
			return  json(["code"=>403,"msg"=>"请添加地址"]);
		}
		
	}
	
	//获取自提地址
	function  getztaddress(){
		$address = db('address')->where('shop_id',input('agent_id'))->select(); 
		return  json(["code"=>200,"data"=>$address]);
	}
	
	//提交订单
	public function tjorder(){
		if ($this->request->isPost()) {
			$postdata = $this->request->post();
			
			$addcount = db('member_address')->where('user_id',session('user_id'))->select();
			if(!$addcount){
				return json(["code"=>403,'msg'=>'请先设置地址!']);	
			}			
			
//			$pay_type = input('post.pay_type');
//			if (!$pay_type) {
//				$this->error('请选择支付方式');
//			}

			$result = true;
			Db::startTrans();
			
			//新增订单
			$userid = 	session('user_id');
			//获取用户信息
			$user_info = db('member')->where('user_id',$userid)->find();
			
			$address = db('member_address')->where('user_id',$userid)->where('is_default', 1)->find();

			$result = true;
			//新增订单
			$order['user_id'] = $userid;
			$order['total_price'] = $postdata['price'];
			$order['agent_id'] = $postdata['agent_id'];
			$agentinfo = db('agent')->where('id',$postdata['agent_id'])->find();
			$order['agent_name'] = $agentinfo['agent_name'];
			$orderNo = build_order_no();
			$order['order_sn'] = $orderNo;
			$order['add_time'] = now_time();
			$order['status'] = 1;  // 1待付款 2待发货 3待收货 4待评价 5已完成 6已关闭7退货
			$order['address'] = $address['address'] ;
			$order['pay_type'] = $postdata['pay_type'];
			$order['ztaddress'] = $postdata['ztaddress'];;
			$order['pay_price'] = $postdata['price'];
			$order['memo'] = $postdata['memo'];
			$order['mobile'] = $user_info['mobile'] ;

			// 增加待付款订单
			$orderId = db('good_order')->insertGetId($order);
			if (!$orderId) {
				$result = false;
			}
			
			if($orderId){
				$goods = isset($postdata['goods'])?$postdata['goods']:null;//商品
				if($goods){
					foreach($goods as $i){
						$items[] = array("add_time"=>now_time(),"thumb"=>$i['logo'],"order_id"=>$orderId,"goods_id"=>$i['id'],"price"=>$i['sale_price'],"total_price"=>$i['sale_price']*$i['num'],"nums"=>$i['num'],"goods_name"=>$i['name'],"tui_id"=>$i['tui_id'],"tui_price"=>$i['tui_price']);
						$sql="update cz_goods set stock =stock - ".$i['num'].",sales=sales+".$i['num']." where goods_id = ".$i['id'];
						DB::execute($sql);
					}
					$orderItems = db('order_items')->insertAll($items);
					if (!$orderItems) {
						$result = false;
					}					
				}					
			}
			
			if($result){
				// 提交事务
				Db::commit();
				
				//短信提醒
//				return json(['code'=>200,'msg'=>'支付成功','order_id'=>$orderId]);
				dump('事务提交ok');
			}else{
				//回滚
	    		Db::rollback();
				return json(['code'=>401,'msg'=>'订单处理失败']);
			}
			
			
//			return json(["code"=>200,'msg'=>'支付成功','order_id'=>$orderId]);
			    
		    // 商品的销量累积
//			db('goods')->where('id',$value['id'])->setInc('sale',$value['goods_num']);
			$this->redirect(url('pay/dopayshop', array('sn' => $orderNo)));
			
		}		
	}
	
	function cancel_order($id){
		if($this->request->isPost()){
			$order_info = db('good_order')->where('id',$id)->find();
			if($order_info){
				 $result = db('good_order')->where('id',$order_info['id'])->update(['status'=>8]);
				 if($result){
				 	return json(['code'=>200,'msg'=>'订单已取消']);
				 }else{
				 	return json(['code'=>403,'msg'=>'订单取消失败']);
				 }
			}else{
				return json(['code'=>403,'msg'=>'订单不存在，数据异常']);
			}
		}
	}
	//订单退货
	function tui_order($id){
		if($this->request->isPost()){
			$order_info = db('good_order')->where('id',$id)->find();
			if(!$order_info){
				return json(['code'=>403,'msg'=>'订单不存在，数据异常']);
			}
			$result = true;
			
			Db::startTrans();
			
			$atoalresult = db('member')->where('user_id',$order_info['user_id'])->setInc('money',$order_info['pay_price']);	
			$atoalresult1 = db('member')->where('user_id',$order_info['user_id'])->setInc('total_income',$order_info['pay_price']);			
			if(!$atoalresult){
				$result = false;
			}
			if(!$atoalresult1){
				$result = false;
			}
			if($atoalresult){
				//添加会员资金变化日志
				$data['user_id'] = session('user_id');
				$data['balance'] = $order_info['pay_price']; //变化金额
				$data['order_sn'] = $order_info['order_sn']; // 订单号  提现无订单
				$data['order_type'] = 3; //类型  1支付红包 2 余额抵扣
				$data['message'] = '订单退货';//消息
				$data['add_time'] = now_time();	
				$rest = db('member_charge')->insert($data);	
			}
			if(!$rest){
				$result = false;
			}
			//修改订单状态
			$data2['status'] = 8;
			$data2['confirm_time'] = now_time();
			$result1 = db('good_order')->where('id', $order_info['id'])->update($data2);
			if(!$result1){
				$result = false;
			}
			
			if($result){
				// 提交事务
			    Db::commit();    
			    return json(['code'=>200,'msg'=>'订单退货成功']);
				
			}else{
				// 回滚事务
			    Db::rollback();
			    return json(['code'=>200,'msg'=>'订单已取消']);
			}
			
			
			
			
		}
	}
	
		
	/**
	 * 收货
	 */
	function qrorder($id) {
		if($this->request->isPost()) {
			if (!is_numeric($id)) {
				$this->error('参数错误');
			}			
			$order_info = db('good_order')->where('id',$id)->find();
			if (!$order_info) {
				return json(['code'=>403,'msg'=>'产品不存在或已收货']);
			}
			
			$result = $this->orderFengy($order_info);
			
			if ($result) {
				return json(['code'=>200,'msg'=>'收货成功']);
			} else {
				return json(['code'=>403,'msg'=>'收货失败']);
			}			

		}
	}
	
	//订单奖金处理
	protected function orderFengy($order) {
		//待确认订单
		if($order['status']==3){
			// 判断订单状态, 如果订单未做过处理, 则处理自己核心业务
			$result = true;
			
			Db::startTrans();
			
			//获取订单金额
			$pay_price = $order['pay_price'];
			
			//添加商家资金变化日志
			$adata['agent_id'] = $order['agent_id'];
			$adata['balance'] = $pay_price; //变化金额
			$adata['order_sn'] = $order['order_sn']; // 订单号
			$adata['order_type'] = 1;//订单
			$adata['message'] = '用户下单';//奖金
			$adata['add_time'] = now_time();
			
			$aresult = db('agent_charge')->insert($adata);												

			if(!$aresult){
				$result = false;
			}				
			
			//订单剩余金额计入商家余额
			$abalanceresult = db('agent')->where('id',$order['agent_id'])->setInc('balance', $adata['balance']);			
			if(!$abalanceresult){
				$result = false;
			}
			
			//订单剩余金额计入商家累计收入
			$atoalresult = db('agent')->where('id',$order['agent_id'])->setInc('total_income', $adata['balance']);			
			if(!$atoalresult){
				$result = false;
			}
						
			
			//修改订单状态
			$data['status'] = 6;
			$data['confirm_time'] = now_time();
			$result = db('good_order')->where('id', $order['id'])->update($data);
			if(!$result){
				$result = false;
			}
			
			if($result){
				// 提交事务
			    Db::commit();    
				
			}else{
				// 回滚事务
			    Db::rollback();
			    $this->error('收货失败');
			}
			return $result;	
		}
	}

	public function ordertj(){
		if ($this->request->isPost()) {
			$postdata = $this->request->post();
			
			$agent_id = $postdata['agent_id'];
			$price = $postdata['price'];
			$fenyongs = $postdata['fenyongs'];
			$goods = isset($postdata['goods'])?$postdata['goods']:null;//商品
			cookie('goodscar',$goods);
			$data['agent_id'] = $agent_id;
			$data['sfprice'] = $price;
			$data['fenyongs'] = $fenyongs;
			return json(['code'=>200,'msg'=>'操作成功','data'=>$data]);
		}	
	
		return $this->fetch();	
	}
	
	public function orderzf(){
		$this->assign('agent_id', input('agent_id'));
		$info = db('agent')->where('id', input('agent_id'))->find();
		$this->assign('info', $info);
		
		
		$this->assign('price', input('sfprice'));
		$this->assign('fenyongs', input('fenyongs'));
		$this->assign('user_id', session('user_id'));
		$this->assign('datea', date("Y-m-d",strtotime("+1 day")));
		$this->assign('timea', date("h:i"));
		$this->assign('dateb', date("Y-m-d"));
		$this->assign('timeb', date("h:i"));
		//查询用户信息
		$memberInfo = db('member')->where('user_Id',session('user_id'))->find();
		
		//检查会员是否抵扣 true 有 fasle 没有
		$flag = check_money($memberInfo);
			
		$this->assign('flag', $flag);
		$this->assign('memberInfo', $memberInfo);
		
		//获取省份信息
		$province_list = db('sys_district')->where('pid',0)->select(); 
		
		$province_ids = "";
		foreach($province_list as $kye=>$value){
			$province_ids = $province_ids.$value['id'].",";
		}
		
		//获取市信息
		$city_list = db('sys_district')
						->where('pid','in', substr($province_ids ,0,strlen($province_ids)-1))
						->select(); 
						
		$district_ids = "";
		foreach($city_list as $kye=>$value){
			$district_ids = $district_ids.$value['id'].",";
		}			
						
		//获取区县信息
		$district_list = db('sys_district')
						->where('pid','in', substr($district_ids ,0,strlen($district_ids)-1))
						->select(); 		
	
		$this->assign('province_list', $province_list);
		$this->assign('city_list', $city_list);
		$this->assign('district_list', $district_list);
		return $this->fetch();
	}
	
	
	//调用微信支付 
	public function order_buy(){
		if ($this->request->isPost()) {
			$result = true;
			Db::startTrans();
			//新增订单
			$userid = session('user_id');
			//获取用户信息
			$user_info = db('member')->where('user_id',$userid)->find();
			
			$address = db('member_address')->where('user_id',$userid)->where('is_default', 1)->find();
			if(!$address){
				$result = false;
			}

			$result = true;
			//新增订单
			$order['user_id'] = $userid;
			$order['total_price'] = input('ddprice');
			$order['agent_id'] = input('agent_id');
			$agentinfo = db('agent')->where('id',1)->find();
			$order['agent_name'] = $agentinfo['agent_name'];
			$orderNo = build_order_no();
			$order['order_sn'] = $orderNo;
			$order['add_time'] = now_time();
			$order['status'] = 1;  // 1待付款 2待发货 3待收货 4待评价 5已完成 6已关闭7退货
			$order['address'] = $address['province'].$address['city'].$address['district'].$address['address'] ;
			$order['pay_type'] = 1;//input('pay_type');
			$order['ztaddress'] = input('ztads');
			$order['pay_price'] = input('ddprice');
			$order['memo'] = input('memo');
			$order['mobile'] = $user_info['mobile'] ;
			$order['consignee'] = $address['consignee'];
			$order['fenyongs'] = input('fenyongs');
			$order['ps_time'] = input('datea').':'.input('timea');
			
			// 增加待付款订单
			$orderId = db('good_order')->insertGetId($order);
			if (!$orderId) {
				$result = false;
			}
			
			if($orderId){
				$goods = cookie('goodscar');//商品
				if(!$goods){
					$this->error('账单为空');
				}
				if($goods){
					foreach($goods as $i){
						$items[] = array("tui_id"=>$i['tui_id'],"tui_price"=>$i['tui_price'],"add_time"=>now_time(),"thumb"=>$i['logo'],"order_id"=>$orderId,"goods_id"=>$i['id'],"price"=>$i['sale_price'],"total_price"=>$i['sale_price']*$i['num'],"nums"=>$i['num'],"goods_name"=>$i['name']);
						$sql="update cz_goods set stock =stock - ".$i['num'].",sales=sales+".$i['num']." where goods_id = ".$i['id'];
						DB::execute($sql);
					}
					$orderItems = db('order_items')->insertAll($items);
					if (!$orderItems) {
						$result = false;
					}					
				}					
			}
			
			if($result){
				// 提交事务
				Db::commit();
				
				//短信提醒
				dump('事务提交ok');
			}else{
				//回滚
	    		Db::rollback();
				$this->error('订单处理失败');
			}
			
			$members = db('member')->where('user_id', $order['user_id'])->find();
			$flag = check_money($members);
			if($members['money'] >= input('ddprice')){
				$order = db('good_order')->where('order_sn',$orderNo)->find();
				$handlerResult2 = db('good_order')->where('order_sn', $order['order_sn'])->update(array(
				'status' => 2,
				'pay_time' => now_time()
				));
				
				//检查会员是否抵扣 true 有 fasle 没有
				//添加会员资金变化日志
				$data['user_id'] = $order['user_id'];
				$data['balance'] = $order['pay_price']; //变化金额
				$data['order_sn'] = $order['order_sn']; // 订单号  提现无订单
				$data['order_type'] = 2; //类型  1支付红包 2 余额抵扣
				$data['message'] = '会员余额抵扣';//消息
				$data['add_time'] = now_time();	
				$rest = db('member_charge')->insert($data);	
				$yuemoney = $members['money'] - $order['pay_price'];
				$rest2 = db('member')->where('user_id', $order['user_id'])->update(array('money' => $yuemoney));
	
	
				//更新完订单的状态后，需要将该订单所获取的积分给到购买的会员用户end
				//个人分配奖金
				//会员余额变化日志
				if(input('fenyongs')){
					$member = db('member')->where('user_id', $order['user_id'])->find();
					$num = input('fenyongs')*0.1;
					//添加会员资金变化日志
					$data['user_id'] = $order['user_id'];
					$data['balance'] = $num; //变化金额
					$data['order_sn'] = $order['order_sn']; // 订单号  提现无订单
					$data['order_type'] = 1; //类型  1支付红包 //1提现2二维码付款3提现失败4返现5分佣
					$data['message'] = '会员支付红包';//消息
					$data['add_time'] = now_time();	
					$rest = db('member_charge')->insert($data);	
					$yue_money = $member['money'] + $num;
					$rest4 = db('member')->where('user_id', $member['user_id'])->update(array('money' => $yue_money));
					
					
					$memberpid = db('member')->where('user_id', $member['pid1'])->find();
					
					if($memberpid && $memberpid['denji'] == 3){
						$numpid = input('fenyongs')*0.9;
						$datapid['user_id'] = $memberpid['user_id'];
						$datapid['balance'] = $numpid; //变化金额
						$datapid['order_sn'] = $order['order_sn']; // 订单号  提现无订单
						$datapid['order_type'] = 1; //类型  1支付红包 //1提现2二维码付款3提现失败4返现5分佣
						$datapid['message'] = '会员购买奖励';//消息
						$datapid['add_time'] = now_time();	
						$restpid = db('member_charge')->insert($datapid);	
						$yue_moneypid = $memberpid['money'] + $numpid;
						$rest4 = db('member')->where('user_id', $memberpid['user_id'])->update(array('money' => $yue_moneypid));
					}
					
				}
				//推荐分佣
				$rest5 = db('order_items')->where('order_id', $orderId)->select();
				
				foreach($rest5 as $i){
					if($i['tui_id']){
						$memberpid = db('member')->where('user_id', $i['tui_id'])->find();
						if($memberpid && $memberpid['denji'] == 3){
							$numpid = $i['tui_price'];
							$datapid['user_id'] = $memberpid['user_id'];
							$datapid['balance'] = $numpid; //变化金额
							$datapid['order_sn'] = $order['order_sn']; // 订单号  提现无订单
							$datapid['order_type'] = 1; //类型  1支付红包 //1提现2二维码付款3提现失败4返现5分佣
							$datapid['message'] = '会员商品推荐奖励';//消息
							$datapid['add_time'] = now_time();	
							$restpid = db('member_charge')->insert($datapid);	
							$yue_moneypid = $memberpid['money'] + $numpid;
							$rest4 = db('member')->where('user_id', $memberpid['user_id'])->update(array('money' => $yue_moneypid));
						}
					}
					
				}
				
				
				
				$this->redirect(url('pay/pay_success', array('sn' => $orderNo)));
				
			}else{
				$this->redirect(url('pay/dopayshop', array('sn' => $orderNo)));
			}
				
		}
	}
	
	//调用微信支付 
	public function order_shenji(){
		if ($this->request->isPost()) {
			$userid = session('user_id');
			$order['uid'] = $userid;
			$order['money'] = 299;
			$order['add_time'] = now_time();
			$order['order_sn'] = build_order_no();
			$result = db('order_shenji')->insertGetId($order);
			if($result){
				$this->redirect(url('pay/dopayshenji', array('sn' => $order['order_sn'])));
			}else{
				$this->error('订单处理失败');
			}
		}
	}
	
	//修改获取地址
	public function getadsbyid() {
		$address_list =db('member_address')
						->where('user_id',session('user_id'))
						->where('is_default',1)
						->select();
		//获取省份信息
		$province_list = db('sys_district')->where('pid',0)->select(); 
		
		$province_ids = "";
		foreach($province_list as $kye=>$value){
			$province_ids = $province_ids.$value['id'].",";
		}
		
		//获取市信息
		$city_list = db('sys_district')
						->where('pid','in', substr($province_ids ,0,strlen($province_ids)-1))
						->select(); 
						
		$district_ids = "";
		foreach($city_list as $kye=>$value){
			$district_ids = $district_ids.$value['id'].",";
		}			
						
		//获取区县信息
		$district_list = db('sys_district')
						->where('pid','in', substr($district_ids ,0,strlen($district_ids)-1))
						->select(); 		
	
		$this->assign('province_list', $province_list);
		$this->assign('city_list', $city_list);
		$this->assign('district_list', $district_list);
		$data['adslist'] = $address_list;
		$data['province_list'] = $province_list;
		$data['city_list'] = $city_list;
		$data['district_list'] = $district_list;
		return json(['code'=>200,'data'=>$data]);
	}
	
	public function yue_record(){
		if($_POST){
				$list =db('member_charge')
						->where('user_id',session('user_id'))->page(input('page'),10)
						->order('add_time desc')
						->select();
				foreach($list as $k=>$v	){
					$list[$k]['order_type']=get_type_charge($list[$k]['order_type']);
				}
				return json(["list"=>$list]);
		}
		$data =db('member')
						->where('user_id',session('user_id'))
						->field('money')->find();
		$this->assign('data', $data);	
		$list =db('member_charge')
						->where('user_id',session('user_id'))->page(1,10)
						->order('add_time desc')
						->select();
		$this->assign('list', $list);
		return $this->fetch();	
	}
	public function sheng_chuanye(){
		if(request()->isPost()){
			$data = input('post.');
			$datas['denji'] = 3;
			$datas['add_time'] = now_time();
			$result = db('member')->where('user_id', session('user_id'))->update($datas);
			if($result){
				return json(['code'=>200,'msg'=>'申请成功']);
			}else{
				return json(['code'=>405,'msg'=>'申请失败']);
			}
		}
		
		
		
		return $this->fetch();	
	}
	public function sheng_vip(){
		if(request()->isPost()){
			$data = input('post.');
			$datas['pid1'] = $data['pid1'];
			$datas['denji'] = 2;
			$datas['add_time'] = now_time();
			$result = db('member')->where('user_id', session('user_id'))->update($datas);
			if($result){
				return json(['code'=>200,'msg'=>'申请成功']);
			}else{
				return json(['code'=>405,'msg'=>'申请失败']);
			}
		}
		return $this->fetch();	
	}
	public function invite(){
		$data= db('member')->where('user_id', session('user_id'))->find();
		$this->assign('data',$data);
		$list= db('member')->where('pid1', session('user_id'))->select();
		$this->assign('list',$list);
		return $this->fetch();	
	}
	public function tui_agent(){
		if(request()->isPost()) {
			$data = input('post.');
			$datas['agent_name'] = $data['agent_name'];
			$datas['pc_name'] = $data['pc_name'];
			$datas['tel'] = $data['tel'];
			$datas['uid'] = session('user_id');
			$datas['add_time'] = now_time();
			$result = db('shenagent')->insert($datas);
			if($result){
				return  json(["code"=>200,"msg"=>"申请成功,等管理员审核"]);
			}else{
				return  json(["code"=>403,"msg"=>"申请失败"]);
			}
		}
		return $this->fetch();	
	}
	
	
	
}
